package com.lebang.aop;

import com.lebang.common.Shirox;
import com.lebang.mapper.LbbAuthorityMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

@Aspect
@Component
public class ShiroxAop {
	
	@Autowired
	private LbbAuthorityMapper mapper;

	@Pointcut("@annotation(com.lebang.common.Shirox)")
	public void jp() {}
	
	/**
	 * 环绕通知
	 * @author weizx  
	 * @date 2018年7月5日 下午3:28:35  
	 * @param point
	 * @return
	 * @throws Throwable
	 */
	@Around("jp()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
		HttpSession session  = request.getSession();
		String userid = (String) session.getAttribute("userid");
		MethodSignature signature = (MethodSignature) point.getSignature();  
		Method method = signature.getMethod();
		Shirox shirox = method.getAnnotation(Shirox.class);
		if (shirox!=null) {
			String resource = shirox.value();
			int ishas = mapper.ishas(userid, resource);
			if (ishas==0) {
				response.setStatus(404);
				return null;
			}
		}
		return point.proceed();
	}
}
